#!/bin/bash
# Convert a MSYS path list to Windows-native format.
# Status is zero if successful, nonzero otherwise.

# Copyright (C) 2013-2025 Free Software Foundation, Inc.

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

# Take only the basename from the full pathname
me=${0//*\//}

usage="usage: ${me} PATHLIST"

help="$usage
  or:  ${me} OPTION

Convert a MSYS path list to Windows-native format.

PATHLIST should be a colon-separated list of MSYS paths, which will be
written to the standard output after performing these transformations:

1. Discard empty paths.
2. Replace: '\' with '/', '//' with '/' and ':' with ';'.
3. Translate absolute paths to Windows-native format.

Options:
  --help     display this help and exit

Report bugs to <bug-gnu-emacs@gnu.org>."

for arg
do
  case $arg in
    --help | --hel | --he | --h)
      exec echo "$help" ;;
    --)
      shift
      break ;;
    -*)
      echo "${me}: invalid option: $arg" >&2
      exit 1 ;;
    *)
      break ;;
  esac
done

[ $# -eq 1 ] || {
    echo "${me}: $usage" >&2
    exit 1
}

w32pathlist=""

# Put each MSYS path in one positional parameter and iterate through
# them
IFS=:
set -- $1

for p
do
    [ -z "$p" ] && continue

    if [ "${p:0:1}" != "/" ]
    then
	w32p=$p
    elif [ -d "$p" ]
    then
	w32p=$(cd "$p" && pwd -W)
    else
	# Make some cleanup in the path and look for its deepest
	# existing directory

	p=${p//\\//}
	p=${p//\/\///}
	p=${p%/}

	p1=$p
	while :
	do
	    p1=${p1%/*}
	    [ -z "$p1" ] && p1="/" && break
	    [ -d "$p1" ] && break
	done

	# translate the existing part and append the rest
	w32p=$(cd "${p1}" && pwd -W)
	remainder=${p#$p1}
	w32p=${w32p%/}/${remainder#/}
    fi

    w32pathlist="${w32pathlist};${w32p}"

done

echo "${w32pathlist:1}"
